Template = {}

Template.open = function(file)
	if Template.database then
		for _, stmt in Template.queryCache do
			stmt:finalize()
		end
		Template.database:close()
	end
	Template.database = sqlite3.open(file, true)

	if not Template.database then
		Log.warn("Lua.Util.Template", "Fail to open template file " .. file)
		return false
	end
	Template.queryCache = {}
	return true
end

Template.read = function(query, parameters)
	assert(type(query) == "string", "Template query mush be a string")

	if not Template.database then
		Log.warn("Lua.Util.Template", "Template is not open")
		return false
	end

	local stmt = Template.queryCache[query]
	if not stmt then
		stmt = Template.database:prepare(query)
		if stmt then
			Template.queryCache[query] = stmt
		else
			Log.warn("Lua.Util.Template", Template.database:errmsg())
			return false
		end
	end

	if parameters then
		if stmt:bind_names(parameters) ~= sqlite3.OK then
			Log.warn("Lua.Util.Template", Template.database:errmsg())
			return false
		end
	end

	stmt:step()
	stmt:reset()

	local count, result = 0, {}
	for row in stmt:nrows() do
		count = count + 1
		table.insert(result, row)
	end
	return true, count, result
end
